using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class UI_CraftPreview : MonoBehaviour
{
    [SerializeField] private Image itemIcom;
    [SerializeField] private TextMeshProUGUI itemName;
    [SerializeField] private TextMeshProUGUI itemDescription;

    private UI_CraftMaterialSlot[] craftMaterialSlots;
    private Inventory_Storage storage;
    private Inventory_Item itemToCraft;


    public void ConfirmCraft()
    {
        if (itemToCraft == null)
            return;
        if (storage.CanCraftItem(itemToCraft))
            storage.CraftItem(itemToCraft);

        UpdateAllMaterialSlots();
    }
    public void SetupCraftPreview(Inventory_Storage storage)
    {
        this.storage = storage;
        craftMaterialSlots = GetComponentsInChildren<UI_CraftMaterialSlot>(true);
        foreach (var slot in craftMaterialSlots)
            slot.gameObject.SetActive(false);
        
    }
    public void UpdatePreview(Inventory_Item itemToCraft)
    {
        this.itemToCraft = itemToCraft;
        itemIcom.sprite = itemToCraft.itemData.itemIcon;
        itemName.text = itemToCraft.itemData.itemName;

        itemDescription.text = itemToCraft.GetDescription();
    }
    
    public void UpdateAllMaterialSlots()
    {
        foreach (var slot in craftMaterialSlots)
            slot.gameObject.SetActive(false);

        for (int i = 0; i < itemToCraft.itemData.materials.Length; i++)
        {
            int totalMaterialCount = storage.GetMaterialTotalQuantity(itemToCraft.itemData.materials[i].materialData);
            craftMaterialSlots[i].UpdateMaterialSlot(itemToCraft.itemData.materials[i], storage, totalMaterialCount);
            craftMaterialSlots[i].gameObject.SetActive(true);
        }
    }
}
